import pytz

from django.utils import timezone

from .utils import get_setting, SettingsManager


class TimezoneMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, req):
        try:
            tzone = pytz.timezone(get_setting('TIMEZONE') or 'UTC')
        except pytz.UnknownTimeZoneError:
            tzone = pytz.utc

        timezone.activate(tzone)
        return self.get_response(req)


class RefreshSettingsMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, req):
        # Update all settings from database (to sync all gunicorn multiprocesses settings with database)
        SettingsManager.update_all_settings()
        return self.get_response(req)
